import { useContext } from "react";
import { Suspense, useEffect } from "react";
import { useRoutes, Navigate, useLocation, useNavigate } from "react-router-dom"
import { Context } from "../App";
import LayoutIndex from "../pages/layout/LayoutIndex";
import Login from "../pages/Login";
import PlayerAdd from "../pages/player/PlayerAdd";
import PlayerList from "../pages/player/PlayerList";
import ScriptCreate from "../pages/scripts/ScriptCreate";
import ScriptsList from "../pages/scripts/ScriptsList";
import Timeslot from "../pages/timeslot/timeslot";
import UserList from "../pages/user/userList";
function RouterConfig() {

  // 获取全局state
  let { state, dispatch } = useContext(Context);
  let { token } = state

  // 全局校验
  // let token = localStorage.getItem("token");
  let navigate = useNavigate()
  let location = useLocation()
  // console.log(location);

  useEffect(() => {
    if (!token && location.pathname != "/login") {
      // 触发跳转
      console.log("触发跳转", location.pathname);
      // 触发dispatch设置登录后需要调回的页面
      navigate("/login")
      dispatch({ type: "setNavPath", payload: location.pathname });
    }
  }, [])



  let routes = useRoutes([
    {
      path: '/',
      element: <LayoutIndex></LayoutIndex>,
      children: [
        // react中没有重定向，可以使用以下配置实现跳转
        {
          path: '',
          element: <Navigate to="/player/list"></Navigate>
        },
        {
          path: "/player/list",
          element: <PlayerList></PlayerList>
        },
        {
          path: "/player/add",
          element: <PlayerAdd></PlayerAdd>
        },
        {
          path: "/scripts/list",
          element: <ScriptsList></ScriptsList>
        },
        {
          path: "/scripts/create",
          element: <ScriptCreate></ScriptCreate>
        },
        {
          path: "/user/list",
          element: <UserList></UserList>
        },
        {
          path: "/timeslot",
          element: <Timeslot></Timeslot>
        }
      ]
    },
    {
      path: "/login",
      element: <Login></Login>
    }


  ])
  return (
    <Suspense>
      {routes}
    </Suspense>

  );
}

export default RouterConfig;